package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheckConfirm;
import com.fingard.dsp.bank.reqrespobj.balancecheckconfirm.ReqBalCheckConfirmQry;
import com.fingard.dsp.bank.reqrespobj.balancecheckconfirm.RetAtsBalCheckConfirmQry;
import com.fingard.dsp.bank.reqrespobj.balancecheckconfirm.detail.RetAtsBalCheckConfirmDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * @author DELL on 2019-09-24.
 * @version 1.0
 */
public class CMB01BalanceCheckConfirm extends CMB01Base implements IBalanceCheckConfirm {
    @Override
    public RetAtsBalCheckConfirmQry d_7509_BalCheckConfirm(ReqBalCheckConfirmQry p_req7509) throws Exception {
        //余额对账确认返回ATS的对象
        RetAtsBalCheckConfirmQry retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
        	
            CMB01OtherElse tmpOtherElse = new CMB01OtherElse();
            tmpOtherElse.reqHeader = p_req7509.reqHeader;
            tmpOtherElse.bankFront = this.bankFront;
            tmpOtherElse.sbLog = this.sbLog;
            String tmpBUSMOD = this.getBankConfig().getValueAsString("busmodBAL");
            if(StringHelper.isNullOrEmpty(tmpBUSMOD)){
                tmpBUSMOD = tmpOtherElse.getBUSMOD("N35010");
            }

            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTNSTOPR";
            while (p_req7509.readRecord()) {
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(xmlWriter, tmpBnkHeader);
                xmlWriter.writeStartElement("NTOPRMODX");
                xmlWriter.writeElementString("BUSMOD", tmpBUSMOD);//业务模式
                xmlWriter.writeEndElement();
                xmlWriter.writeStartElement("NTNSTOPRX");
                xmlWriter.writeElementString("SQRNBR", p_req7509.readedDetail.iSeqno);//流水号
                xmlWriter.writeElementString("BCHNBR", p_req7509.readedDetail.statementNumber);//批次号
                xmlWriter.writeElementString("BARCOD", p_req7509.readedDetail.barCode);//条形码编号
                xmlWriter.writeElementString("BARSEQ", p_req7509.readedDetail.barSeq);//每页账户顺序号
                xmlWriter.writeElementString("EACNBR", p_req7509.readedDetail.actNum);//账户
                xmlWriter.writeElementString("ACTSEQ", p_req7509.readedDetail.actSeq);//账户序号
                xmlWriter.writeElementString("ACCNBR", p_req7509.readedDetail.accNbr);//活期账号
                xmlWriter.writeElementString("YERMTH", p_req7509.readedDetail.yearMonth);//对账月份
                
              //招行BALFLG余额核对状态：Y余额相符，N余额不符，S调节相符，非Y不符时，原因必输
                //<DZFlag>对账情况（余额核对状态）：2平（余额相符），3不平（余额不符），1未对账，7调节相符</DZFlag>
                String dzFlag = "";
                if ("2".equals(p_req7509.readedDetail.dzFlag)) {
                    dzFlag = "Y";
                } else if ("7".equals(p_req7509.readedDetail.dzFlag)) {
                    dzFlag = "S";
                } else if("3".equals(p_req7509.readedDetail.dzFlag)){
                    dzFlag = "N";
                }
                xmlWriter.writeElementString("BALFLG", dzFlag);//余额核对状态
                String tmpYURREF = p_req7509.readedDetail.busRef;
                if(StringHelper.isNullOrEmpty(tmpYURREF)){
                	tmpYURREF = p_req7509.readedDetail.iSeqno;
                }
                xmlWriter.writeElementString("YURREF", tmpYURREF);
                
              //余额核对不符原因
                if ("2".equals(p_req7509.readedDetail.dzFlag))
                {
                	xmlWriter.writeElementString("ADJCAS", "00000");
                }
                else
                {/*      <DeDZFlag>明细对账情况（未达帐、疑义帐）
                       1-企业已收款银行未收款入账款项
                       2-企业已付款银行未付款记账款项
                       3-银行已收款、企业尚未收款记账（未达账项）
                       4-银行已收款、企业尚未收款记账（疑义明细）
                       5-银行已付款、企业尚未付款记账（未达账项）
                       6-银行已付款、企业尚未付款记账（疑义明细）
                       7-其它</DeDZFlag>
                  
                  ADJCAS 余额调节原因类型
    余额不符原因类型，固定5位字符（xxxxx），每一位代表一种原因，选择用1，不选用0，
    	            第1位表示“客户已收账，银行未收账”，即10000
    	            第2位表示“客户未收账，银行已收账”，即01000
    	            第3位表示“客户未付账，银行已付账”，即00100
    	            第4位表示“客户已付账，银行未付账”，即00010
    	            第5位表示“其它”，                  即00001
    	            举例：选中前两种原因时，传值为11000；
    		    余额相符时，则为00000
                  */
                    if ("1".equals(p_req7509.readedDetail.deDZFlag))
                    {
                    	xmlWriter.writeElementString("ADJCAS", "10000");
                    }
                    else if ("2".equals(p_req7509.readedDetail.deDZFlag))
                    {
                    	xmlWriter.writeElementString("ADJCAS", "00010");
                    }
                    else if ("3".equals(p_req7509.readedDetail.deDZFlag) || "4".equals(p_req7509.readedDetail.deDZFlag))
                    {
                    	xmlWriter.writeElementString("ADJCAS", "01000");
                    }
                    else if ("5".equals(p_req7509.readedDetail.deDZFlag) || "6".equals(p_req7509.readedDetail.deDZFlag))
                    {
                    	xmlWriter.writeElementString("ADJCAS", "00100");
                    }
                    else
                    {
                    	xmlWriter.writeElementString("ADJCAS", "00001");
                    }
                }
                xmlWriter.writeElementString("TELNBR", p_req7509.readedDetail.telNbr);
                xmlWriter.writeElementString("LOGTXT", p_req7509.readedDetail.notConfirmReason);

                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                        String returnInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                        if ("0".equals(returnCode)) {
                            RetAtsBalCheckConfirmDetail tmpRetDetail = new RetAtsBalCheckConfirmDetail();
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = returnInfo;
                            tmpRetDetail.actNum = p_req7509.readedDetail.actNum;
                            String tmpSQRNBR = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/SQRNBR");
                            tmpRetDetail.iSeqno = tmpSQRNBR;
                            tmpRetDetail.bnkReqNo = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/REQNBR");
                            tmpRetDetail.oprSeqNo = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/OPRSQN");
                            tmpRetDetail.oprAlias = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/OPRALS");

                            tmpRetDetail.result = "5";
                            String tmpREQSTS = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/REQSTS");
                            String tmpRTNFLG = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/RTNFLG");
                            
                            if ("FIN".equalsIgnoreCase(tmpREQSTS))
                            {
                                if ("S".equalsIgnoreCase(tmpRTNFLG))
                                {
                                	tmpRetDetail.result = "2";
                                }
                                else if ("F".equalsIgnoreCase(tmpRTNFLG) || "B".equalsIgnoreCase(tmpRTNFLG) || "R".equalsIgnoreCase(tmpRTNFLG) || "D".equalsIgnoreCase(tmpRTNFLG) || "C".equalsIgnoreCase(tmpRTNFLG) || "M".equalsIgnoreCase(tmpRTNFLG) || "V".equalsIgnoreCase(tmpRTNFLG))
                                {
                                	tmpRetDetail.result = "3";
                                }
                            }
                            else
                            {
                            	tmpRetDetail.result = "4";
                            }
                            tmpRetDetail.dzFlag = "2";
                            tmpRetDetail.retCode = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/ERRCOD");
                            tmpRetDetail.retMsg = tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/ERRTXT");
                            
                            if(!p_req7509.readedDetail.iSeqno.equals(tmpBkReader.getFirstText("/CMBSDKPGK/NTOPRRTNZ/SQRNBR"))){
                            	tmpRetDetail.respCode = "-1";
                            	tmpRetDetail.respInfo = "银行返回流水号" + tmpSQRNBR + "与提交流水号" + p_req7509.readedDetail.iSeqno + "不一致";
                            }
                            retAts.writeRetDetail(tmpRetDetail, p_req7509.isBatch);
                        } else {
                            retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
                            retAts.writeStart();//写返回ATS的统一头部信息
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(returnInfo);
                        }
                    } else {
                        retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
                        retAts.writeStart();//写返回ATS的统一头部信息
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpSbMsg.toString());
                    }
                } else {
                    retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
                    retAts.writeStart();//写返回ATS的统一头部信息
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpRetBkStr[1]);
                }
            }
        } catch (Exception e) {
            retAts = new RetAtsBalCheckConfirmQry(p_req7509.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            this.WriteBankLogLn(e);
        }
        retAts.writeEnd();
        return retAts;
    }
}
